package seqlist.oj;

/**
 * 合并链表
 */
public class Num21 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 先判断边界条件
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        // 此时l1和l2都不为空
        ListNode dummyHead = new ListNode(-1);
        // 尾插
        ListNode last = dummyHead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                last.next = l1;
                last = l1;
                l1 = l1.next;
            }else {
                last.next = l2;
                last = l2;
                l2 = l2.next;
            }
        }
        // 此时说明l1或者l2为空
        if (l1 == null) {
            last.next = l2;
        }
        if (l2 == null) {
            last.next = l1;
        }
        return dummyHead.next;
    }
}
